﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Text;
using System.Threading.Tasks;

namespace Flagwind.ComponentModel
{
	public class EmailHelper
	{
		/// <summary>
		/// 群发邮件
		/// </summary>
		/// <param name="fromEmail">发件人邮箱地址</param>
		/// <param name="password">发件人邮箱密码</param>
		/// <param name="host">SMTP</param>
		/// <param name="email">收件人地址，邮件以‘,’分割</param>
		/// <param name="body">邮件内容</param>
		/// <param name="subject">邮件标题</param>
		public static void SendMail(string fromEmail, string password, string host, string email, string body, string subject)
		{
			using(var smtp = new SmtpClient())
			{
				using(var mail = new MailMessage())
				{
					//发件人邮箱地址
					MailAddress Messagefrom = new MailAddress(fromEmail);  
					mail.From = Messagefrom;

					//密送 邮件以‘,’分割
					mail.Bcc.Add(email);

					//标题和内容，注意设置编码，因为默认编码是ASCII
					mail.Subject = subject;
					mail.SubjectEncoding = Encoding.UTF8;

					//HTML内容
					mail.Body = body;
					mail.BodyEncoding = Encoding.UTF8;

					//指示改电子邮件内容是HTML格式
					mail.IsBodyHtml = true;

					//SMTP设置（根据邮箱类型设置，这里是Live Mail的SMTP服务器地址）
					smtp.Host = host;
					smtp.UseDefaultCredentials = false;

					//某些SMTP服务器可能不支持SSL，会抛出异常
					//smtp.EnableSsl = true;

					smtp.Credentials = new NetworkCredential(fromEmail, password);
					smtp.DeliveryMethod = SmtpDeliveryMethod.Network;

					//发送
					smtp.Send(mail);
				}
			}
		}
	}
}
